import Vue from 'vue'
import Vuex from 'vuex'
import request from '@/utils/request'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}')
  },
  getters: {
    token: state => state.token,
    userInfo: state => state.userInfo
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    RESET_TOKEN(state) {
      state.token = ''
      state.userInfo = {}
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  },
  actions: {
    // 登录
    login({ commit }, loginForm) {
      return new Promise((resolve, reject) => {
        request({
          url: '/car-auth/auth/login',
          method: 'post',
          data: loginForm
        })
          .then(response => {
            if (response.code === 200) {
              commit('SET_TOKEN', response.data.token)
              commit('SET_USER_INFO', response.data.userInfo)
              resolve()
            } else {
              reject(response.message || '登录失败')
            }
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 登出
    logout({ commit }) {
      commit('RESET_TOKEN')
    },
    // 重置token
    resetToken({ commit }) {
      commit('RESET_TOKEN')
    }
  }
}) 